﻿var controller = this.lookupController();
var dataList = [];
var gridItem = store.data.items;

//获取当前record相同的值
var sameObj = {};
Ext.each(gridItem, function (record2, i) {
    if (record2.get('DescriptionOfSuppliesServices') && record2.get('Department')) {
        var key = Ext.String.format('{0}_{1}', record2.get('DescriptionOfSuppliesServices'), record2.get('Department'));

        if (Ext.Array.contains(dataList, key)) {
            controller.showMsgTips("Data entry already exists in Project X Allocation.");
            record.data.Department = '';
            record.commit();
        } else {
            dataList.push(key);
            if (record.id != record2.id) {
                key = Ext.String.format('{0}', record2.get('DescriptionOfSuppliesServices'));

                //有值则追加 CompanySharingRatio
                if (sameObj[key]) {
                    sameObj[key] += record2.get('Amount');
                } else {
                    sameObj[key] = record2.get('Amount');
                }
            }
        }
    }
});

//当前编辑的record数据拼接的key.
var currentObj = Ext.String.format('{0}', record.get('DescriptionOfSuppliesServices'));
//匹配到相同key的值
var matchingObj = sameObj[currentObj] || 0;

var originalAmount = record.get('originalAmount');
if (record.get('Amount') + matchingObj > originalAmount) {
    controller.showMsgTips("The sum of allocated items in Project X Allocation must be equal to the total amount of Total Price.");
    var value = record.previousValues || {};
    record.data[context.field] = value[context.field];
} else {

    if ((context.colIdx == 4 || context.colIdx == 7) && record.get(context.field) > 100) {
        var value = record.previousValues || {};
        record.data[context.field] = value[context.field];
    } else {
        var jAPer = record.get("JAPer");
        var lRPer = record.get("LRPer");
        var amount = record.get("Amount");

        if (jAPer != null && lRPer != null && amount) {

            if (context.field == 'JAPer') {
                lRPer = 100 - jAPer;
            } else {
                jAPer = 100 - lRPer;
            }

            var jaamount = (amount * jAPer / 100);
            var lramount = (amount * lRPer / 100);

            record.data.JAAmount = jaamount;
            record.data.LRAmount = lramount;
            record.data.JAPer = jAPer;
            record.data.LRPer = lRPer;
        }
    }
}
//JA是 291开头  LR是 191开头
if (context.field == 'Department') {
    record.data.CostCenterForJA = record.data.Department.replace('191-', '291-');
    record.data.CostCenterForLR = record.data.Department;
} else if (context.field == 'CostCenterForJA') {

    record.data.CostCenterForLR = context.value.replace('291-', '191-');

} else if (context.field == 'CostCenterForLR') {

    record.data.CostCenterForJA = context.value.replace('191-', '291-');

}
record.commit();